#include "Hero.h"
#include "../mainScreen/CommonDefinition.h"
#include <algorithm>

#define HERO_HP_MAX 800

Hero::Hero()
	:m_pHeroNode(NULL), m_pHeroBody(NULL), m_iHP(HERO_HP_MAX), m_iSV(100), m_pHeroAction(NULL)
{
}

Hero::~Hero()
{
}

Hero* Hero::create(const cocos2d::Vec2 &pos)
{
	Hero *ret = new (std::nothrow) Hero();
	if (ret && ret->init(pos))
	{
		ret->autorelease();
		return ret;
	}
	else
	{
		CC_SAFE_DELETE(ret);
		return nullptr;
	}
}

bool Hero::init(const cocos2d::Vec2 &pos)
{
	if (cocos2d::Node::init()){

		m_pHeroNode = cocos2d::CSLoader::createNode("player/hero/hero.csb");
		m_pHeroNode->setScale(30.0 / m_pHeroNode->getBoundingBox().size.width);

		m_pHeroBody = cocos2d::PhysicsBody::createBox(m_pHeroNode->getBoundingBox().size);
		m_pHeroAction = cocos2d::CSLoader::createTimeline("player/hero/hero.csb");

		m_pHeroBody->setTag(HERO_PHYBODY_TAG);
		m_pHeroBody->setCategoryBitmask(HERO_COLLISION_MASK);
		m_pHeroBody->setCollisionBitmask(HERO_COLLISION_MASK);
		m_pHeroBody->setContactTestBitmask(CONTACT_MASK);
		m_pHeroBody->setPositionOffset(cocos2d::Vec2(0, m_pHeroNode->getBoundingBox().size.height / 2));
		//m_pHeroBody->setPositionOffset(cocos2d::Vec2(m_pHeroNode->getPosition().x, m_pHeroNode->getPosition().y + m_pHeroNode->getBoundingBox().size.height / 2));
		m_pHeroNode->setPhysicsBody(m_pHeroBody);
		m_pHeroNode->setPosition(pos);
		m_pHeroAction->play("stand", true);
		m_pHeroNode->runAction(m_pHeroAction);

		m_pHeroBody->setDynamic(false);

		addChild(m_pHeroNode);
		return true;
	}
	return false;
}

void Hero::dealCollisionWithEnemy(int hpDec)
{
	setHeroHP(hpDec);

	if (m_iHP <= 0)
	{
		scheduleOnce(schedule_selector(Hero::heroDead), 3.0f);
		m_pHeroAction->play("die", false);

	}
	else
	{
		m_pHeroAction->play("hurt", false);
		m_pHeroAction->setLastFrameCallFunc(CC_CALLBACK_0(Hero::hurtResponseCallback, this));
	}
}

void Hero::heroDead(float delta)
{
	unschedule(schedule_selector(Hero::heroDead));
}

void Hero::setHeroHP(int hp)
{
	m_iHP = std::min(hp, HERO_HP_MAX);
	m_iHP = std::max(hp, 0);
}



int Hero::getHeroHP()
{
	return m_iHP;
}

void Hero::setHeroSV(int sv)
{
	m_iSV = std::min(sv, 0);
}

int Hero::getHeroSV()
{
	return m_iSV;
}

void Hero::attackStart()
{
	m_pHeroAction->play("attack", false);
	m_pHeroAction->setLastFrameCallFunc(CC_CALLBACK_0(Hero::attackResponseCallback, this));
}

void Hero::hurtResponseCallback()
{
	m_pHeroAction->clearLastFrameCallFunc();
	m_pHeroAction->play("stand", true);
}

void Hero::attackResponseCallback()
{
	m_pHeroAction->clearLastFrameCallFunc();
	m_pHeroAction->play("stand", true);
}